﻿ 
   // Define a property to hold the Home state
HomeControl.prototype.home_ = null;
 
// Define setters and getters for this property
HomeControl.prototype.getHome = function() {
  return this.home_;
}

function HomeControl(controlDiv, map, home) {
 
  // We set up a variable for this since we're adding
  // event listeners later.
  var control = this;
  
  // Set the home property upon construction
  control.home_ = home;
 
  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';
 
  // Set CSS for the control border
  var goHomeUI = document.createElement('DIV'); 
  goHomeUI.style.backgroundColor = 'white';
  goHomeUI.style.borderStyle = 'solid';
  goHomeUI.style.borderWidth = '2px';
  goHomeUI.style.cursor = 'pointer';
  goHomeUI.style.textAlign = 'center';
  goHomeUI.title = 'Click to set the map to Home';
  controlDiv.appendChild(goHomeUI);
 
  // Set CSS for the control interior
  var goHomeText = document.createElement('DIV');
  goHomeText.style.fontFamily = 'Arial,sans-serif';
  goHomeText.style.fontSize = '12px';
  goHomeText.style.paddingLeft = '4px';
  goHomeText.style.paddingRight = '4px';
  goHomeText.innerHTML = '<b>Home</b>';
  goHomeUI.appendChild(goHomeText);
 
  // Setup the click event listener for Home:
  // simply set the map to the control's current home property.
  google.maps.event.addDomListener(goHomeUI, 'click', function() {
    var currentHome = control.getHome();
    map.setCenter(currentHome);
  });
}


   
    function replaceNbsps(str) { 
      var re = new RegExp(String.fromCharCode(160), "g"); 
      return str.replace(re, ''); 
    } 
 
      function objetoAjax( ){
	    var http = false;
	    //Use IE's ActiveX items to load the file.
	    if(typeof ActiveXObject != 'undefined') {
		    try {http = new ActiveXObject("Msxml2.XMLHTTP");}
		    catch (e) {
			    try {http = new ActiveXObject("Microsoft.XMLHTTP");}
			    catch (E) {http = false;}
		    }
	    //If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
	    } else if (XMLHttpRequest) {
		    try {http = new XMLHttpRequest();}
		    catch (e) {http = false;}
	    }
	    return http;
    }
 
    
    function enviarMapa(url, parametros){ 
            ajax = objetoAjax();
    		var flag = true;         
            ajax.open("POST", url, true);
            
    		ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		    ajax.setRequestHeader("Content-length", parametros.length);
		    ajax.setRequestHeader("Connection", "close");
		    
            ajax.onreadystatechange=function() {
				   //alert(ajax.readyState);
				   //alert(ajax.status);
			       if (ajax.readyState == 4 && flag){// && ajax.status == 200
                           fntDatosServidor(ajax.responseText); 
                           flag = false; 
                   }
            }
            ajax.send(parametros);
    }
    
    
    function trim( cadena ) {
        var retorno = cadena.replace(/^\s+/g,'');
        return retorno.replace(/\s+$/g,''); 
    }
    
   function getFecha(fecha, hora){ 
        if( trim( fecha ) != ''){
         return fecha + ' ' + hora;
        }
        return '';
    }

    function aHover(tr) {
            
           $(tr).hover(
	            function () {
		            $(tr).addClass('hover');
	            }, 
	            function () {
		            $(tr).removeClass('hover');
	        }
	      ); 
	      
       }
       
    function mostrarListaUsuario( obj ){ 
         
         if( $(obj).next().is(':visible') ) {
            $(obj).next().hide( ); 
         }else{
            $(obj).next().show( ); 
         } 
     }
               
     function item(obj){
         $(obj).addClass('hover');
     }
     
     	function keypressFecha(obj, e){ 
           var  keyAscii = e.which;
           var texto = obj.value;
           if( ((texto.length == 2) || (texto.length) == 5) &&  keyAscii != 8 && keyAscii != 0  ) {
   	          if(keyAscii<48 || keyAscii>57 ){
			        return false;
	          }else{
			        obj.value = obj.value + "/";
	          }
           } else{
              if( ( keyAscii<48 || keyAscii>57 ) &&  keyAscii != 8 && keyAscii != 0 && keyAscii != 47){
		        return false;
              }
           } 
    }
    
    function mostrarImagen( obj ){
         $(".image").hover(function( ) {                   
                    var image = $(this).attr("rel");
                    //$('#image').hide();
                    $('#image').fadeIn();//'slow'
                    $('#image').html('<img src="' + image + '"/>');
                return false;
	        });
     }
  
     
//////////////////////////////////////////////////////////////////////     
      var map;

      var latlonServidor = new Array( );
      var aMarkets = new Array( );
      var datosServidor = new Array( );
      
      var aTrack = new Array( );
      var latitudIni = - 12.0462037802177;
      var longitudIni = -77.0656585693359;
      
    function initialize( ) {   
    
         try {InicializarCoordenadas(); }
	     catch (e) {}
    
         var settings = { 
		    mapTypeControl: true,
		    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		    navigationControl: true,
		    scaleControl: true,
		    mapTypeId: google.maps.MapTypeId.ROADMAP
	      };
	    map = new google.maps.Map(document.getElementById("map"), settings);
		map.setCenter(new google.maps.LatLng(latitudIni, longitudIni)); // longitudIni-122.1419
	    map.setZoom(8);			
	    map.enableKeyDragZoom();
	    
	    // INICIO HOME
        var LugarInicio = map.getCenter();
        var homeControlDiv = document.createElement('DIV');
        var homeControl = new HomeControl(homeControlDiv, map, LugarInicio);
 
        homeControlDiv.index = 1;
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);
        //FIN HOME
}  
   
    function buscarPuntosRepetidos(sec, latlon){
			
			var arregloPuntosRepetidos = new Array( );
			
			 for(var i=0; i<latlonServidor.length; i++){
		        //busca repetidos excepto el suyo
				if(latlonServidor[i] == latlon && sec != i){
					arregloPuntosRepetidos[arregloPuntosRepetidos.length] = i;
				}
			}
			//pone el suyo propio
			if(arregloPuntosRepetidos.length > 0 ){
				arregloPuntosRepetidos[arregloPuntosRepetidos.length] = sec;
			} 
			
			return arregloPuntosRepetidos;
			
   }
   
     function clearOverlays( ) {
     
      if (aTrack) {
        for (var i=0; i< aTrack.length; i++) {
          aTrack[i].setMap(null);
        }
      }
     
      if (aMarkets) {
        for (var i=0; i< aMarkets.length; i++) {
          aMarkets[i].setMap(null);
        }
      }
      
        latlonServidor.length = 0;
        aMarkets.length = 0;
        datosServidor.length = 0;
    }
   
   
   function fntDatosServidor(datos){ 
   
     clearOverlays( ); 
     
     if(""+datos.length <= 0) return;
    
     datosServidor =  datos.split(";");
     
     var arregloTrack = new Array( );
    
     for (var i=0; i < datosServidor.length ; i++) {
            var arrCoordenada = datosServidor[i].split("|"); 
            var lat = arrCoordenada[0];
            var lon = arrCoordenada[1]; 
            
            if( i == ( datosServidor.length - 1 ) ){
                map.setCenter(new google.maps.LatLng(eval(lat),eval(lon)));
            }
           // $('#mensajess').html( 'new GLatLng('+lat+', '+lon+'), ' +  $('#mensajess').html());
           arregloTrack[i] = new google.maps.LatLng(eval(lat), eval(lon));
           //map.addOverlay(createMarker( i, lat, lon ));
           createMarker( i, lat, lon );
           
           if(!isultimaPosicion( ))
            {
            crearPolyline(datosServidor[i]);
            }
     }
     
  
//     if(isultimaPosicion( )){
//        color ="none";
//     }

     if(!isultimaPosicion( ))
     {
//         var polyline = new GPolyline(arregloTrack, color, 3, 1);
//         map.addOverlay(polyline);
//         
         
            var flightPath = new google.maps.Polyline({
            path: arregloTrack,
            strokeColor: "#ff0000",
            strokeOpacity: 1.0,
            strokeWeight: 2
           });

          flightPath.setMap(map);
          
          aTrack.push(flightPath);
     }
     
        // INICIO HOME
        var LugarInicio = map.getCenter();
        var homeControlDiv = document.createElement('DIV');
        var homeControl = new HomeControl(homeControlDiv, map, LugarInicio);
 
        homeControlDiv.index = 1;
        map.controls[google.maps.ControlPosition.TOP_RIGHT].pop();
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);
        //FIN HOME
     
  }
  
  function crearPolyline(datosTemporales){
        
       // alert(datosTemporales);
        
        var arrDatosTotal = datosTemporales.split("$$"); 
			
		if( !(arrDatosTotal.length >1 && arrDatosTotal[1] !=  '')){
		    return;
		}
		//alert(arrDatosTotal[1] );
			
       var tmpArray = arrDatosTotal[1].split("@"); 
      // alert(tmpArray );
       
       var arregloTemp = new Array( );
       
       for (var i=0; i < tmpArray.length ; i++) {
            var arrCoordenada = tmpArray[i].split("|"); 
            var lat = arrCoordenada[0];
            var lon = arrCoordenada[1]; 
             
           // $('#mensajess').html( 'new GLatLng('+lat+', '+lon+'), ' +  $('#mensajess').html());
           arregloTemp[i] = new google.maps.LatLng(eval(lat), eval(lon));
     }
   
//     var polyline = new GPolyline(arregloTemp, "#00ff00", 3, 1);
//     
//     map.addOverlay(polyline);

      var flightPath = new google.maps.Polyline({
        path: arregloTemp,
        strokeColor: "#00ff00",
        strokeOpacity: 1.0,
        strokeWeight: 2
      });

      flightPath.setMap(map);
      
      aTrack.push(flightPath);
     
  }
  
  	function createMarker(sec, lat, lon) { 
  	    
  	  // var marker = new GMarker(new google.maps.LatLng(eval(lat), eval(lon)), new GIcon(G_DEFAULT_ICON) );
  	   var marker = new google.maps.Marker({
          position: new google.maps.LatLng(eval(lat), eval(lon)), 
          map: map
       });
          
      latlonServidor[sec] = lat+'|'+lon;   
      aMarkets[sec] = marker; 
      
  //    alert("----->   <div id='infos'>"+ parsearDatosShowRepetidos(sec, lat, lon)+ "</div>");
      
      var infowindow = new google.maps.InfoWindow({
        content: "<div id='infos'>"+ parsearDatosShowRepetidos(sec, lat, lon)+ "</div>"
       });
      
      google.maps.event.addListener(marker, "click", function( ) {
        infowindow.open(map, marker);
      });
      return marker;
    }
            
   function parsearDatosShowRepetidos(sec, lat, lon){  
        var cadena ="";
    	
        var repetidos = buscarPuntosRepetidos(sec, lat+'|'+lon);
        
//        alert('repetidos ' + repetidos);
        
	        if(repetidos.length > 0){
		        ///cadena = "<div class='title'> PUNTOS </div>";
		        for(var i=0; i < repetidos.length; i++){
		            //if(eval(repetidos[i]) >= 0 ){
		           cadena = cadena + 
		                    " <div class='section1'>" +
		                    "<a href='#'  onmouseover='aHover(this);' onclick='showMarkerRepeat(" + repetidos[i] + ");'>" + 
		                    "INDEX : " + ( eval(repetidos[i]) + 1 )+" </a> </div>" ;
		            //} 
		        }
	        }else{
        	         cadena = showMessageDialog(sec, datosServidor[sec]);
	        }  
	     
         return cadena;
   }
           
   function showMarkerRepeat(indice){
     var infowindow = new google.maps.InfoWindow({
        content: "<div id='infos'>" + showMessageDialog(indice, datosServidor[indice]) + "</div>"
       });
        
      infowindow.open(map,aMarkets[indice]);
      
   }
	

